package cn.conac.rc.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.conac.rc.entity.UnderCategoryEntity;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.repository.UnderCategoryRepository;

@Service
public class UnderCategoryService extends GenericService<UnderCategoryEntity, Integer> {

	@Autowired
	private UnderCategoryRepository underCategoryRepository;

	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @param mapTree
	 * @return 一级内设机构List
	 */
	public List<UnderCategoryEntity> findMapTree(Map<String,Object> mapTree) {
		mapTree.put("id", 0);
		mapTree.put("name", underCategoryRepository.findUnderCategoryRootName().getName());

		List<Map<String, Object>> childCategoryList= new ArrayList<Map<String, Object>>();
		Map<String, Object> categorytMap = null;
		List<UnderCategoryEntity> underCategoryList  = underCategoryRepository.findByPidOrderByIdAsc(0);
		for(UnderCategoryEntity underCategoryEntity: underCategoryList){
			categorytMap = new HashMap<String, Object>();
			categorytMap.put("id",underCategoryEntity.getId());
			categorytMap.put("name",underCategoryEntity.getName());
			// 递归调用枝干节点
			if(new Integer(0).equals(underCategoryEntity.getLeaf())){
				recursiveCategoryTree(underCategoryEntity.getId(), categorytMap);
			}
		    childCategoryList.add(categorytMap);
		}
		mapTree.put("children",childCategoryList);
		return underCategoryList;
	}
	
	/**
	 * 根据主键ID递归查询level2一下的内设机构信息
	 * @param id
	 * @param map
	 * @return 返回以该ID为父的内设机构List
	 */
	public  List<UnderCategoryEntity> recursiveCategoryTree(Integer id, Map<String,Object> map) {
	     List<UnderCategoryEntity> underCategoryList = underCategoryRepository.findByPidOrderByIdAsc(id);
	     List<Map<String, Object>> childCategoryList= new ArrayList<Map<String, Object>>();
	     Map<String, Object> categoryMap = null;
	     for(UnderCategoryEntity categoryEntity : underCategoryList){
	    	 categoryMap = new HashMap<String, Object>();
			 categoryMap.put("id",categoryEntity.getId());
			 categoryMap.put("name",categoryEntity.getName());
			 // 递归调用枝干节点
			 if(new Integer(0).equals(categoryEntity.getLeaf())){
				 recursiveCategoryTree(categoryEntity.getId(),categoryMap);
			 }
	    	 childCategoryList.add(categoryMap);
	     }
	     map.put("children",childCategoryList);
	     return underCategoryList;
	}

}
